package cn.dream.ebag.MessengerLib;

import android.support.annotation.NonNull;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import cn.dream.ebag.MessengerLib.listeners.OnServerListener;

/**
 * @ProjectName: MessengerServer
 * @Package: cn.dream.mgserver
 * @Author: qktang
 * @CreateDate: 2021/1/13 14:28
 * @Description: 描述
 */
public class MSCallbackMgr {

    private static MSCallbackMgr instance;

    private ConcurrentMap<String, OnServerListener> cacheListener = new ConcurrentHashMap<>();

    public static MSCallbackMgr getInstance() {
        if (instance == null) {
            synchronized (MSCallbackMgr.class) {
                instance = new MSCallbackMgr();
            }
        }
        return instance;
    }

    public void addServerListener(OnServerListener listener, @NonNull String tag) {
        if (cacheListener == null) {
            cacheListener = new ConcurrentHashMap<>();
        }
        if (cacheListener.get(tag) != null) {
            cacheListener.remove(tag);
        }
        cacheListener.put(tag, listener);
    }

    public void sendServerJsonMsg(String jsonMsg, String clientTag) {
        if (cacheListener == null || cacheListener.size() < 1) {
            return;
        }
        Set<String> tagList = cacheListener.keySet();
        for (String tag : tagList) {
            OnServerListener listener = cacheListener.get(tag);
            if (listener != null) {
                listener.onJsonMsg(clientTag, jsonMsg);
            }
        }
    }

    public void sendServerErrorMsg(String jsonMsg, String clientTag) {
        if (cacheListener == null || cacheListener.size() < 1) {
            return;
        }
        Set<String> tagList = cacheListener.keySet();
        for (String tag : tagList) {
            OnServerListener listener = cacheListener.get(tag);
            if (listener != null) {
                listener.onErrorMsg(clientTag, jsonMsg);
            }
        }
    }

    public void sendNewClientMsg(String clientTag) {
        if (cacheListener == null || cacheListener.size() < 1) {
            return;
        }
        Set<String> tagList = cacheListener.keySet();
        for (String tag : tagList) {
            OnServerListener listener = cacheListener.get(tag);
            if (listener != null) {
                listener.onNewClient(clientTag);
            }
        }
    }

    public void sendClientList(List<String> clientTagList) {
        if (cacheListener == null || cacheListener.size() < 1) {
            return;
        }
        Set<String> tagList = cacheListener.keySet();
        for (String tag : tagList) {
            OnServerListener listener = cacheListener.get(tag);
            if (listener != null) {
                listener.onUpdateClientList(clientTagList);
            }
        }
    }
}
